package cn.ezios.huo.s3;

import cn.ezios.huo.s3.core.HuoStorageCoreWrapper;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.S3Configuration;
import software.amazon.awssdk.services.s3.presigner.S3Presigner;

import java.net.URI;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@Configuration
@ConfigurationProperties(prefix = "s3")
public class StorageConfiguration {

    public StorageConfiguration() {
        log.info("StorageConfiguration init");
    }

    @Setter
    private String accessKey;
    @Setter
    private String secretKey;
    @Setter
    private String endpoint;
    @Setter
    private String region;

    @Bean
    public ExecutorService virtualThreadExecutorService() {
        return Executors.newVirtualThreadPerTaskExecutor();
    }

    @Bean
    public S3AsyncClient s3AsyncClient() {
        return S3AsyncClient.builder()
                .region(Region.of(region))
                .credentialsProvider(
                        StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, secretKey))
                )
                .endpointOverride(java.net.URI.create(endpoint))
                .build();
    }

    @Bean
    public S3Presigner s3Presigner(S3AsyncClient client){
        return S3Presigner.builder()
                .endpointOverride(URI.create(endpoint))
                .credentialsProvider(client.serviceClientConfiguration().credentialsProvider())
                .region(client.serviceClientConfiguration().region())
                /**
                 * [AWS S3 配置]
                 * 对象存储服务商请求头不支持x-amz-te
                 * https://blog.csdn.net/tarryck/article/details/115674402
                 */
                .serviceConfiguration(S3Configuration.builder().checksumValidationEnabled(false).pathStyleAccessEnabled(true).build())
                .build();
    }

    @Bean
    public HuoStorageCoreWrapper huoStorageCoreWrapper(){
        return new HuoStorageCoreWrapper();
    }

}
